package com.jetpackframework.request;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public abstract class RequestUtil<R,T extends RequestCache<R>> {
    private ExecutorService executor;
    private MyRunable runable = new MyRunable();
    protected RequestUtil(){
        executor = Executors.newCachedThreadPool();
    }

    public void send(R task){
        if (getCache().hasNext()) {
            getCache().add(task);
            execTaskExecutor();
        }else {
            if (runable.isExit){
                execTask(task);
            }else {
                getCache().add(task);
                execTaskExecutor();
            }

        }
    }

    private void execTaskExecutor() {
        if (!runable.isExit){
            executor.execute(runable);
        }
    }


    private class MyRunable implements Runnable{
        private boolean isExit;
        @Override
        public void run() {
            while(true){
                if (getCache().hasNext()){
                    isExit = true;
                    execTask(getCache().get());
                    try {
                        Thread.sleep(80);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else {
                    isExit = false;
                    return;
                }
            }
        }
    }

    protected abstract void execTask(R task);

    protected abstract T getCache();

    public void close(){
        getCache().caches.clear();
        executor.shutdown();
        executor = null;
    }
}
